package main

import (
	"context"
	"fmt"
	"log"
	"sync"
	"time"

	"github.com/go-redis/redis/v8"
)

// Redis 配置
const (
	RedisHost     = "localhost"
	RedisPort     = "6380"
	RedisPassword = "mhSCk0NheGhmtsha" // 替换为你的密码
	PoolSize      = 50                 // 连接池大小
	TestCount     = 100                // 测试请求次数
)

var (
	rdb *redis.Client
	ctx = context.Background()
)

func initRedis() {
	rdb = redis.NewClient(&redis.Options{
		Addr:         RedisHost + ":" + RedisPort,
		Password:     RedisPassword,
		DB:           0, // 默认数据库
		PoolSize:     PoolSize,
		DialTimeout:  5 * time.Second,
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 5 * time.Second,
	})

	// 测试连接
	_, err := rdb.Ping(ctx).Result()
	if err != nil {
		log.Fatalf("Failed to connect to Redis: %v", err)
	}
}

func testRedisConnection(wg *sync.WaitGroup) {
	defer wg.Done()

	// 写入测试数据
	err := rdb.Set(ctx, "test_key", "test_value", 0).Err()
	if err != nil {
		fmt.Printf("Error setting key: %v\n", err)
		return
	}

	// 读取测试数据
	val, err := rdb.Get(ctx, "test_key").Result()
	if err != nil {
		fmt.Printf("Error getting key: %v\n", err)
		return
	}

	fmt.Printf("Success: %s\n", val)
}

func main() {
	startTime := time.Now()

	// 初始化 Redis 连接
	initRedis()
	defer rdb.Close()

	// 模拟并发请求
	var wg sync.WaitGroup
	wg.Add(TestCount)

	for i := 0; i < TestCount; i++ {
		go testRedisConnection(&wg)
	}

	// 等待所有 goroutine 完成
	wg.Wait()

	elapsed := time.Since(startTime)
	fmt.Printf("Test completed in %.2f seconds\n", elapsed.Seconds())
}